#include "config.h"
#include <cjson/cJSON.h>
#include <malloc.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

static config_t *conf = NULL;

static void handlehttpitem(cJSON *item) {
  cJSON *portitem = cJSON_GetObjectItem(item, "port");
  cJSON *maxclientnumitem = cJSON_GetObjectItem(item, "maxclientnum");

  conf->http_port = portitem->valueint;
  conf->http_maxclientnum = maxclientnumitem->valueint;
}

static void handleandroiditem(cJSON *item) {
  cJSON *portitem = cJSON_GetObjectItem(item, "port");
  cJSON *maxclientnumitem = cJSON_GetObjectItem(item, "maxclientnum");

  conf->android_port = portitem->valueint;
  conf->android_maxclientnum = maxclientnumitem->valueint;
}

config_t *readconf() {
  if (conf != NULL) {
    return conf;
  }

  conf = malloc(sizeof(config_t));

  conf->http_port = 8080;
  conf->http_maxclientnum = 10;
  conf->android_port = 8081;
  conf->android_maxclientnum = 10;
  strncpy(conf->music_file_path, "/var/Music", sizeof(conf->music_file_path));

  FILE *fp = fopen(CONFIFG_FILE, "r");

  if (fp == NULL) {
    fprintf(stderr, "[%s, %d] failed to open config file\n", __FILE__,
            __LINE__);
    return conf;
  }

  char jsonstr[255];
  char ch;
  int n = 0;

  while ((ch = fgetc(fp)) != EOF) {
    jsonstr[n++] = ch;
  }

  fclose(fp);

  cJSON *root = cJSON_Parse(jsonstr);

  if (!root) {
    fprintf(stderr, "[%s, %d] %s\n", __FILE__, __LINE__, cJSON_GetErrorPtr());
    return conf;
  }

  cJSON *httpitem = cJSON_GetObjectItem(root, "http");
  cJSON *androiditem = cJSON_GetObjectItem(root, "android");
  cJSON *music_file_path_item = cJSON_GetObjectItem(root, "music_file_path");
  strncpy(conf->music_file_path, music_file_path_item->valuestring,
          sizeof(conf->music_file_path));

  handlehttpitem(httpitem);
  handleandroiditem(androiditem);

  cJSON_Delete(root);

  return conf;
}
